package com.ostrich.demomvvm.net

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @Author : yaotianxue
 * @Time : On 2023/10/18 15:02
 * @Description : RetrofitManager
 */
class RetrofitManager {
    companion object{
        //java中双重锁单例
        val instance:RetrofitManager by lazy(LazyThreadSafetyMode.SYNCHRONIZED){
            RetrofitManager()
        }
    }
    private val retrofit:Retrofit
    //初始化代码块只会执行一次
    init {
        retrofit = Retrofit.Builder()
            .baseUrl("http://10.161.9.80:7012")
            .client(createOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(LiveDataCallAdapterFactory.create())//livedata
            .build()
    }

    private fun createOkHttpClient():OkHttpClient{
        return OkHttpClient.Builder()
            .readTimeout(60,TimeUnit.SECONDS)
            .writeTimeout(60,TimeUnit.SECONDS)
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build()
    }

    //传入不同的api接口创建对应
    fun <T> createService(service:Class<*>):T{
        return retrofit.create(service) as T
    }





}